<?php
/**
 * Description: 申论 - 教师批改作业模块
 * User: devforma
 * Date: 16/5/26
 * Time: 12:05
 */

require __DIR__ . '/ProcessExerciseBase.class.php';

class ShenlunLectorModule extends ProcessExerciseBase {

    /**
     * 设置作业类型
     */
    protected function setExerciseType() {
        $this->data['exercise_type'] = 1;
    }

    /**
     * 设置作业题目
     */
    protected function setExerciseQuestion() {
        global $cmsdb;

        //获取题目和材料
        $questionInfo = $cmsdb->getRow('SELECT `id`, `question`, `answer`, `parent` FROM `original_ztk_shenlun_questions` WHERE `id`=:id', array(':id' => $this->questionIds[0]));
        $materialInfo = $cmsdb->getRow('SELECT `id`, `notice`, `information` FROM `original_ztk_shenlun_questions` WHERE `id`=:id', array(':id' => $questionInfo->parent));

        $this->data['question'] = array(
            'question_id' => (int)$questionInfo->id,
            'notice'      => $materialInfo->notice,
            'material'    => $materialInfo->information,
            'question'    => $this->removeShenlunQNum($questionInfo->question),
            'answer'      => $questionInfo->answer
        );
    }

    /**
     * 设置提交权限
     */
    protected function setSubmitPriv() {
        global $uddb, $cmsdb;

        if (!empty($this->exerciseInfo->constraint_ids)) { //本任务有前置任务

            $constraintIds = explode(',', $this->exerciseInfo->constraint_ids);
            $parentExerciseId = $cmsdb->getVar("select constraint_ids from data_primary_exercise where id=:cId",[':cId' => $constraintIds[0]]);
            //完成单题突破的用户数量  小于三人时跳过任务前置
            $dantitupoCount = $uddb->getVar("select count(*) from history_primary_question_review where exercise_id=:eId and status in (1, 5)",
                [':eId' => $parentExerciseId]);

            if ($dantitupoCount >= 3) {
                //查询用户完成的前置任务数
                $sql = "SELECT COUNT(*) FROM `history_user_primary_exercise`
            WHERE `exercise_id` IN ({$this->exerciseInfo->constraint_ids}) AND `user_id`={$this->userId} AND `status`IN (1, 5)";
                $doneCount = $uddb->getVar($sql);

                if ($doneCount < count(explode(',', $this->exerciseInfo->constraint_ids))) { //如果前置任务未全做完,则本任务不可做
                    $this->data['can_submit'] = false;
                    $this->data['pre_exercises'] = [];

                    $preExercises = $cmsdb->getResults("SELECT `id`, `name` FROM `data_primary_exercise` WHERE `id` IN ({$this->exerciseInfo->constraint_ids})");
                    foreach ($preExercises as $exercise) {
                        $this->data['pre_exercises'][] = array('exercise_id' => (int)$exercise->id, 'exercise_name' => $exercise->name);
                    }

                } else {
                    parent::setSubmitPriv();
                }
            }else {
                parent::setSubmitPriv();
            }

        } else {
            parent::setSubmitPriv();
        }
    }

    /**
     * 设置用户答案
     */
    protected function setUserAnswer() {
        global $uddb;

        //查询用户做题记录
        $sql = 'SELECT * FROM `history_primary_question_review` WHERE `user_id`=:uid AND `exercise_id`=:eid LIMIT 1';
        $questionRecord = $uddb->getRow($sql, array(':uid' => $this->userId, ':eid' => $this->exerciseId));

        if (!empty($questionRecord)) { //有用户答题记录
            $answer = array(
                'origin' => array(
                    'submit_time' => $questionRecord->action_time,
                    'images'      => explode('#', $questionRecord->user_answer)
                )
            );

            //批改信息
            if (!empty($questionRecord->reviewer_id)) {
                $answer['review'] = array(
                    'lector'        => $this->getLectorInfo($questionRecord->reviewer_id),
                    'review_time'   => $questionRecord->review_time,
                    'images'        => explode('#', $questionRecord->review_content),
                    'review_postil' => nl2br((string)$questionRecord->review_postil),
                    'score'         => (int)$questionRecord->review_score
                );
            }

            $answer['is_collected'] = (int)$questionRecord->is_collected;

            $this->data['user_answer'] = $answer;
        }
    }

    /**
     * 检测提交的参数
     * @param array $args 参数
     * @return bool
     */
    public function validateArgs($args) {
        if (!empty($args['image_url']) && !empty($args['question_id'])) {
            $this->submitArgs = $args;
            return true;
        }

        return false;
    }

    /**
     * 提交 - 设置作业状态
     */
    protected function setSubmitStatus() {
        if ($this->exerciseInfo->end_time > $this->now)
            $this->submitExerciseRecord['status'] = 3; //已提交
        else
            $this->submitExerciseRecord['status'] = 5; //过期完成
    }

    /**
     * 提交 - 保存答题记录及设置作业统计信息
     */
    protected function saveQuestionRecordsAndSetSubmitSummary() {
        global $uddb;

        //构造题目记录
        $questionRecord = array(
            'question_id'   => $this->submitArgs['question_id'],
            'exercise_id'   => $this->exerciseId,
            'user_id'       => $this->userId,
            'action_time'   => $this->now,
            'user_answer'   => $this->submitArgs['image_url'],
            'reviewer_type' => 0,
            'status'        => 1
        );

        //查询是否存在提交记录
        $sql = 'SELECT `id` FROM `history_primary_question_review` WHERE `user_id`=:uid AND `exercise_id`=:eid LIMIT 1';
        $exists = $uddb->getVar($sql, array(':uid' => $this->userId, ':eid' => $this->exerciseId));

        if ($exists) {
            $uddb->update('history_primary_question_review', $questionRecord, array('id' => $exists));
        } else {
            $uddb->insert('history_primary_question_review', $questionRecord);
        }

        $this->submitExerciseRecord['summary'] = '';
    }

    /**
     * 获取教师信息
     *
     * @param int $letorId 教师id
     * @return array
     */
    private function getLectorInfo($letorId) {
        global $cmsdb;

        $cacheKey = 'vip:func:getLectorInfo:'.$letorId;
        if (($lectorInfo = cacheGet($cacheKey)) == null) {
            $res = $cmsdb->getRow('SELECT `name`, `avatar` FROM `data_teacher` WHERE `id`=:id', array(':id' => $letorId));
            $lectorInfo = array(
                'id'     => (int)$letorId,
                'name'   => $res->name,
                'avatar' => (string)$res->avatar
            );

            cacheAdd($cacheKey, $lectorInfo, 24*60*60);
        }

        return $lectorInfo;
    }
}